from daily import get_daily_df

import pandas as pd

import util.mydecorator
import util.lib as ulib
import util.util as utils

ret = None
writer = None

def built_empty_df():
    return pd.DataFrame({}, columns=['year','stock','year_pct',
                                     'min_date','min_close','min_year_pct',
                                     'max_date','max_close','max_year_pct'])

def task(stock, year):
    global ret
    global writer

    start = year + "-01-01"
    end = year + "-12-31"
    
    df = get_daily_df(stock)

    try:
        last_year_end = df[:start].iloc[-1]

        tmp = df[start:end]
        current_day = tmp.iloc[-1]

        min_day = tmp[tmp['low'] == tmp['low'].min()].iloc[0]
        max_day = tmp[tmp['high'] == tmp['high'].max()].iloc[0]
    except Exception as e:
        print("error", e ,stock, year)
        return
    

    item = {
        "year": year,
        "stock": stock,
        "year_pct": round((current_day['close'] - last_year_end['close']) / last_year_end['close'] * 100, 2),
        "min_date": min_day.name.strftime('%Y-%m-%d'),
        "min_close": min_day['close'],
        "min_year_pct": round((min_day['close'] - last_year_end['close']) / last_year_end['close'] * 100, 2),
        "max_date": max_day.name.strftime('%Y-%m-%d'),
        "max_close": max_day['close'],
        "max_year_pct": round((max_day['close'] - last_year_end['close']) / last_year_end['close'] * 100, 2)
    }

    ret.loc[len(ret)] = item

# 年最低跌幅
def min_year_pct(shares):
    global ret, writer

    ret = built_empty_df()

    years = ["2014","2015","2016","2017","2018","2019","2020","2021","2022","2023","2024","2025"]

    for year in years:
        for v in shares.iterrows():
            stock = v[1]['name']
            task(stock,year)

    ret.to_excel(writer, sheet_name="min_year_pct")

# 年涨跌统计
def year_pct_sta(shares):
    global ret, writer

    ret = pd.DataFrame([], columns=['trade_code', 'name'])

    for item in shares.iterrows():
        stock = item[1]['trade_code']
        stock_name = item[1]['name']
        tag = item[1]['tag']
        wg = item[1]['wg']
        category = item[1]['category']

        df = get_daily_df(stock_name)
        df_year = df[['close']].groupby(lambda x: x.strftime('%Y')).agg(lambda x: x.iloc[-1])

         # 至少有几年的数据
        if len(df_year) >= 2:
            #年
            #df_year = df[['close']].groupby(lambda x: x.strftime('%Y')).agg(lambda x: x[-1])

            df_year['year_pct'] = 100 * (df_year['close'] - df_year['close'].shift(1)) / df_year['close'].shift(1)
            df_year['year_pct'] = round(df_year['year_pct'], 2)
            
            df_year = df_year.sort_index(ascending=False)
            
            tmp = df_year[['year_pct']].T
            tmp['trade_code'] = stock
            tmp['name'] = stock_name
            tmp['tag'] = tag
            tmp['wg'] = wg
            tmp['category'] = category
            
            i = 1
            de_count = 0
            de_pct_sum = 0
 
            while 1:
                # 统计连续下跌月数
                if tmp.iloc[0].iloc[i] < 0:
                    de_pct_sum += tmp.iloc[0].iloc[i]
                    de_count += 1
                    i += 1
                else :
                    break
                    
            tmp['de_count'] = de_count
            tmp['de_pct_sum'] = de_pct_sum + tmp.iloc[0].iloc[0] # 加上本月数据
            
            ret = utils.merge(ret,pd.DataFrame(tmp))

    ret.to_excel(writer, sheet_name="年统计")

@util.mydecorator.calTime
def job():
    global ret
    global writer

    writer = pd.ExcelWriter(ulib.data_path + "year_pct_sat.xlsx")

    shares = ulib.lib_get_all_stock()

    min_year_pct(shares)
    year_pct_sta(shares)

    writer.close()

if __name__ == '__main__':
    job()